<template>
  <div>
    <form action="/">
      <!-- 搜索框 -->
      <van-search
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        @input="onInput"
        @cancel="onCancel"
        @search="onSearch"
      />
      <!-- 搜索结果 -->
      <van-cell
        :title="item.communityName"
        class="cell"
        v-for="(item, index) in searchResult"
        :key="index"
        @click="onClick(item)"
      />
    </form>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { searchCommunityApi } from '@/api'
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      value: '',
      searchResult: []
    }
  },
  computed: {
    ...mapState(['curentCityObj']),
    ...mapState(['rentHouse'])
  },
  watch: {},
  created() {},
  methods: {
    ...mapMutations(['updateRentHouse']),
    // 输入框改变触发
    onInput(val) {
      // this.$toast(val)
      const obj = {
        id: this.curentCityObj.value,
        name: val
      }
      this.searchCommunityFn(obj)
    },
    // 回车触发
    onSearch() {
      // this.searchCommunityFn()
    },
    onCancel() {
      this.$router.back()
    },
    async searchCommunityFn(params) {
      try {
        if (this.value) {
          this.$toast.loading({
            message: '加载中...',
            forbidClick: true
          })
          const { data } = await searchCommunityApi(params)
          // console.log(data.body)
          data.body.forEach((item) => {
            this.searchResult.push(item)
          })
        } else {
          this.searchResult = []
        }
      } catch {
        this.$toast.fail('加载失败,请重试')
      }
    },
    onClick(community) {
      // console.log(community.community)
      // 1、路由传参，并跳转
      this.$router.push({
        path: '/rent',
        query: {
          community
          // noUpdate: true //控制rent页面不清空缓存
        }
      })
      // 不能在这个页面更新本地、vuex的community，不然返回rent页面还是会被清理掉，放在rent页面的提交事件里面
      // 2、存储发布房屋参数
      // const obj = this.rentHouse
      // obj.community = community.community
      // // 3、更新本地数据
      // this.updateRentHouse(obj)
    }
  }
}
</script>

<style scoped lang="less">
.van-cell.cell {
  border-bottom: 1px solid #ddd;
}
</style>
